<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="JVM 堆的那些琐事, Gtwff">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id="></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }

    gtag('js', new Date());
    gtag('config', '');
</script>


    <title>JVM 堆的那些琐事 | Gtwff</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Gtwff</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Gtwff</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://gitee.com/kuangty/kuangty" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://gitee.com/kuangty/kuangty" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/16.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">JVM 堆的那些琐事</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/JVM-%E5%A0%86/">
                                <span class="chip bg-color">JVM 堆</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/JVM/" class="post-category">
                                JVM
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-10-29
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-03-27
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    6.5k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    23 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>咋废话少说，直接进入重点 😃😃😃</p>
<h1 id="一、堆"><a href="#一、堆" class="headerlink" title="一、堆"></a>一、堆</h1><h2 id="1、堆（Heap）的核心概述"><a href="#1、堆（Heap）的核心概述" class="headerlink" title="1、堆（Heap）的核心概述"></a>1、堆（Heap）的核心概述</h2><img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327114401347.png" alt="image-20220327114401347" style="zoom:80%;" />

<h3 id="一、堆的核心概述"><a href="#一、堆的核心概述" class="headerlink" title="一、堆的核心概述"></a>一、堆的核心概述</h3><ul>
<li>一个JVM实例只存在一个堆内存，堆也是Java内存管理的核心区域。</li>
<li>Java堆区在JVM启动的时候即被创建，其空间大小也就确定了。是JVM管理的最大一块内存空间。堆内存的大小是可以调节的。</li>
<li>《Java虚拟机规范》规定，堆可以处理物理上不连续的内存空间中，但在逻辑上它应该被视为连续的</li>
<li>所有的线程共享Java堆，在这里还可以划分线程私有的缓冲区（Thread Local  Allocation Buffer, TLAB)。</li>
<li>《Java虚拟机规范》中对Java堆的描述是：所有的对象实例以及数组都应当在运行时分配在堆上。“几乎”所有的对象实例都在这里分配内存。</li>
<li>数组和对象可能永远不会存储在栈上，因为栈帧中保存引用，这个引用指向对象或者数组在堆中的位置。</li>
<li>在方法结束后，堆中的对象不会马上被移除，仅仅在垃圾收集的时候才会被移除。</li>
<li>堆，是GC（Garbage Collection, 垃圾收集器）执行垃圾回收的重点区域。</li>
</ul>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327114407903.png" alt="image-20220327114407903" style="zoom:80%;" />

<h3 id="二、堆的核心概述：内存细分"><a href="#二、堆的核心概述：内存细分" class="headerlink" title="二、堆的核心概述：内存细分"></a>二、堆的核心概述：内存细分</h3><ul>
<li>现代垃圾收集器大部分都基于分代收集理论设计，堆空间细分为：</li>
<li>Java 7及之前堆内存逻辑上分为三部分：新生区+养老区+永久区<ul>
<li>Young Generation Space  新生区            Young/New<ul>
<li>又被划分为Eden区和Survivor区</li>
</ul>
</li>
<li>Tenure generation space   养老区          Old/Tenure</li>
<li>Permanent Space     永久区        Perm</li>
</ul>
</li>
<li>Java 8 及之后堆内存逻辑上分为三部分：新生区+养老区+元空间<ul>
<li>Young Generation Space  新生区        Young/New<ul>
<li>又被划分为Eden区和Survivor区</li>
</ul>
</li>
<li>Tenure generation space       养老区        Old/Tenure</li>
<li>Meta Space          元空间          Meta</li>
</ul>
</li>
</ul>
<blockquote>
<p>约定：新生区 = 新生代 =  年轻代                 养老区 =  老年区 = 老年代          永久区 =  永久代</p>
</blockquote>
<h3 id="三、堆的内部结构"><a href="#三、堆的内部结构" class="headerlink" title="三、堆的内部结构"></a>三、堆的内部结构</h3><img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327114415132.png" alt="image-20220327114415132" style="zoom:80%;" />

<h2 id="二、设置堆内存大小与OOM"><a href="#二、设置堆内存大小与OOM" class="headerlink" title="二、设置堆内存大小与OOM"></a>二、设置堆内存大小与OOM</h2><h3 id="一、堆空间大小的设置"><a href="#一、堆空间大小的设置" class="headerlink" title="一、堆空间大小的设置"></a>一、堆空间大小的设置</h3><ul>
<li><p>Java堆区用于存储Java对象实例，那么堆的大小在JVM启动时就已经设定好了，大家可以通过选项“-Xmx” 和 “-Xms” 来进行设置。</p>
<ul>
<li>“-Xms” 用于表示堆区的起始内存，等价于 -XX：InitialHeapSize</li>
<li>“-Xmx”则用于表示堆区的最大内存，等价于 -XX：MaxHeapSize</li>
</ul>
</li>
<li><p>一旦堆区中的内存大小超过“-Xmx” 所指定的最大内存时，将会抛出OutOfMemoryError异常。</p>
</li>
<li><p>通常会将 -Xms 和 -Xmx两个参数配置相同的值，其目的是为了能够在java垃圾回收机制清理完堆区后不需要重新分隔计算堆区的大小，从而提高性能。</p>
</li>
<li><p>默认情况下，初始内存大小：物理电脑内存大小 / 64,  最大内存大小：物理电脑内存带下 / 4</p>
</li>
</ul>
<h3 id="二、OutOfMemory举例"><a href="#二、OutOfMemory举例" class="headerlink" title="二、OutOfMemory举例"></a>二、OutOfMemory举例</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">OOMTest</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Picture</span><span class="token punctuation">></span></span> list <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">try</span>  <span class="token punctuation">&#123;</span>
                <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token class-name">List</span><span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Picture</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Random</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">nextInt</span><span class="token punctuation">(</span><span class="token number">1024</span> <span class="token operator">*</span> <span class="token number">1024</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Exception</span> in thread <span class="token string">"main"</span> <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>OutOfMemoryError</span><span class="token operator">:</span><span class="token class-name">Java</span> heap space
	at<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h2 id="三、年轻代与老年代"><a href="#三、年轻代与老年代" class="headerlink" title="三、年轻代与老年代"></a>三、年轻代与老年代</h2><h3 id="一、年轻代与老年代"><a href="#一、年轻代与老年代" class="headerlink" title="一、年轻代与老年代"></a>一、年轻代与老年代</h3><ul>
<li>存储在JVM中的Java对象可以被划分为两类：<ul>
<li>一类是声明周期较短的瞬时对象，这类对象的创建和消亡都非常迅速</li>
<li>另外一类对的生命周期却非常长，在某些极端的情况下还能够与JVM的生命周期保持一致。</li>
</ul>
</li>
<li>Java 堆区进一步细分的话，可以划分为年轻代（YoungGen）和老年代（OldGen)</li>
<li>其中年轻代又可以换分为 Eden 空间、Survivor0 和 Survivor1 空间（有时也叫做 from 区、to 区）。</li>
</ul>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327114421025.png" style="zoom:80%;" />

<ul>
<li>新生代占 1/3、老年代占2/3。其中Eden占新生代的8/10, from区和To区各占1/10</li>
<li>配置新生代与老年代在对结构的占比：<ul>
<li>默认 -XX: NewRaio = 2, 表示新生代占1， 老年代占2， 新生代占整个堆的 1/3</li>
<li>可以修改 -XX: NewRatio = 4, 表示新生代占1， 老年代占4， 新生代占整个堆的1/5</li>
</ul>
</li>
<li>在HotSpot中，Eden空间和另外两个Survivor空间缺省所占的比例是 8:1:1</li>
<li>当然开发人员可以通过选项“-XX:SurvivorRatio” 调整这个空间比例。比如：-XX：SurvivorRatio = 8</li>
<li>几乎所有的Java对象都是Eden区被new出来的。</li>
<li>绝大部分的Java对象的销毁都在新生代进行了，IBM公司的专门研究标明，新生代中80%的对象都是“朝生夕死”的。</li>
<li>可以使用选项“-Xmn”设置新生代最大内存大小，这个参数一般使用默认值就可以了。</li>
</ul>
<h2 id="四、图解对象分配过程"><a href="#四、图解对象分配过程" class="headerlink" title="四、图解对象分配过程"></a>四、图解对象分配过程</h2><h3 id="一、对象分配过程：概述"><a href="#一、对象分配过程：概述" class="headerlink" title="一、对象分配过程：概述"></a>一、对象分配过程：概述</h3><ul>
<li><p>为新对象分配内存时一键非常严谨和复杂的任务, JVM的设计者们不仅需要考虑内存如何分配、在哪里分配等问题，并且由于内存分配算法与内存回收算法密切相关，所以还需要考虑GC执行完内存回收后是否会在内存空间中产生内存碎片。</p>
</li>
<li><p>new 的对象先放在伊甸园区。此区有大小限制。</p>
</li>
<li><p>当伊甸园区的空间填满时，程序又需要创建对象，JVM的垃圾回收器将对伊甸园区进行垃圾回（Minor GC）， 将伊甸园区中的不再被其他对象所引用的对象进行销毁，再加载新的对象放到伊甸园区。</p>
</li>
<li><p>然后将伊甸园中的剩余对象移动到幸存者0区。</p>
</li>
<li><p>如果再次触发垃圾回收，此时上次幸存先来的放到幸存者0区的，如果没有回收，就会放到幸存者1区。</p>
</li>
<li><p>如果再次垃圾回收，此时会重新放到幸存者0区，如果没有回收，就会放到幸存者1区</p>
</li>
<li><p>如果再次经历垃圾回收，此时会重新放回幸存者0区，接着再去幸存者1区。</p>
</li>
<li><p>啥时候能去养老区呢？可以设置次数。默认是15次。可以设置参数：-XX: MaxTenuringThreshold=<N> 进行设置。</p>
</li>
<li><p>在养老区，相对悠闲。当养老区内存不足时，再次触发GC:Major GC，进行养老区的内存清理。</p>
</li>
<li><p>若养老区执行了Major GC之后发现依然无法进行对象的保存，就会产生OOM</p>
</li>
</ul>
<blockquote>
<p>java.lang.OutOfMemoryError：Java Heap space</p>
</blockquote>
<h3 id="二、对象分配过程"><a href="#二、对象分配过程" class="headerlink" title="二、对象分配过程"></a>二、对象分配过程</h3><p>总结：</p>
<ul>
<li>针对幸存者s0, s1区的总结：复制之后又交换，谁空谁是to。</li>
<li>关于垃圾回收：频繁在新生区收集，很少在养老区收集，几乎不在永久区/元空间收集。</li>
</ul>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327114427882.png" alt="image-20220327114427882" style="zoom:80%;" />

<h3 id="三、常用调优工具"><a href="#三、常用调优工具" class="headerlink" title="三、常用调优工具"></a>三、常用调优工具</h3><ul>
<li>JDK命令行</li>
<li>Eclipse：Memory Analyzer Tool</li>
<li>Jconsole</li>
<li>VisualVM</li>
<li>Jprofiler</li>
<li>Java Flight Recorder</li>
<li>GCViewer</li>
<li>GC Easy</li>
</ul>
<h2 id="五、Minor-GC、Major-GC-与-Full-GC"><a href="#五、Minor-GC、Major-GC-与-Full-GC" class="headerlink" title="五、Minor GC、Major GC 与 Full GC"></a>五、Minor GC、Major GC 与 Full GC</h2><p>JVM在进行GC时，并非每次对应上面三个内存（新生代、老年代； 方法区）区域一起回收的，大部分时候回收的都是指新生代。</p>
<p>针对HotSpot VM的实现，它里面的GC按照回收区域又分为两大种类型：一种是部分收集（Partial GC），一种是整堆收集（Full GC)</p>
<p>部分收集：不是完整收集整个Java堆的垃圾收集。其中又分为：</p>
<ul>
<li>新生代（Minor GC/ Young GC）：只是新生代的垃圾收集</li>
<li>老年代收集（Major GC / Old GC）：只是老年代的垃圾收集<ul>
<li>目前，只有CMS GC会有单独收集老年代的行为。</li>
<li>注意，很多时候Major GC 会和Full GC混淆使用，需要具体分辨是老年代回收还是整堆回收。</li>
</ul>
</li>
<li>混合收集（Mixed GC）：收集整个新生代以及部分老年代垃圾收集。<ul>
<li>目前，只有G1 GC会有这种行为。</li>
</ul>
</li>
</ul>
<p>整堆收集（Full GC）：收集整个java堆和方法区的垃圾收集。</p>
<h3 id="二、最简单的分代式GC策略的触发条件"><a href="#二、最简单的分代式GC策略的触发条件" class="headerlink" title="二、最简单的分代式GC策略的触发条件"></a>二、最简单的分代式GC策略的触发条件</h3><p>年轻代GC（Minor GC）触发机制：</p>
<ul>
<li>当年轻代空间不足时，就会触发Minor GC，这里的年轻代满指的是Eden代满，Survivor满不会引发GC。（每次 Minor GC 会清理年轻代的内存）。</li>
<li>因为Java对象大多都具备朝生夕灭的特性，所以Minor GC非常频繁，一般回收速度也比较快。这一定义既清晰又易于理解。</li>
<li>Minor GC会引发STW，暂停其他用户的线程，等垃圾回收结束，用户线程才恢复运行。</li>
</ul>
<p>老年代GC（Major GC/ Full GC）触发机制：</p>
<ul>
<li>指发生在老年代的GC，对象从老年代消失时，我们说“Major GC”或“Full GC”发生了。</li>
<li>出现了Major GC, 经常会伴随至少一次的Minor GC （但非绝对的，在Parallel Scavenge 收集器的收集策略里就有直接进行Major GC的策略选择过程）。<ul>
<li>也就是在老年代空间不足时，会先尝试触发Minor GC 。如果之后空间还不足，则触发Major GC </li>
</ul>
</li>
<li>Major GC的速度一般会比Minor GC慢10倍以上，STW的时间更长。</li>
<li>如果Major GC之后，内存还不足，就报OOM了。</li>
</ul>
<p>Full GC 触发机制：</p>
<p>触发Full GC执行的情况有如下五种：</p>
<ul>
<li>调用System.gc()时，系统建议执行Full GC，但是不必然执行</li>
<li>老年代空间不足</li>
<li>方法区空间不足</li>
<li>通过Minor GC 后进入老年代的可用内存</li>
<li>由于Eden区、survivor space0(From Space) 区向survivor space1（To Space)区复制时，对象大小大于To Space可用内存，则把该对象转存到老年代，且老年代的可用内存小于该对象大小。</li>
</ul>
<blockquote>
<p>说明：full gc是开发或调优中尽量要避免的。这样暂停时间会短一些。</p>
</blockquote>
<h2 id="六、堆空间分代思想"><a href="#六、堆空间分代思想" class="headerlink" title="六、堆空间分代思想"></a>六、堆空间分代思想</h2><h3 id="一、堆空间分代思想"><a href="#一、堆空间分代思想" class="headerlink" title="一、堆空间分代思想"></a>一、堆空间分代思想</h3><p>为什么需要把Java堆分代？不分代就不能正常工作了吗？</p>
<p>经研究，不同对象的生命周期不同。70%~90%的对象是临时对象。</p>
<ul>
<li>新生代：有Eden、两块大小相同的Survivor（又称为from/to, s0/s1）构成，to总为空。</li>
<li>老年代：存放新生代中经历多次GC仍然存活的对象。</li>
</ul>
<p>其实不分代完全可以，分代的唯一理由就是优化GC性能。如果没有分代，那所有的对象都在一块，就如同把一个学校的人都关在一个教室。GC的时候找到哪些对象没用，这就就会对堆的所有区域进行扫描。而很多对象都是朝生夕死的，如果分代的话，把新创建的对象放到某一地方，当GC的时候先把这块存储“朝生夕死”对象的区域进行回收，这样就会腾出很大的空间出来。</p>
<h2 id="七、内存分配策略"><a href="#七、内存分配策略" class="headerlink" title="七、内存分配策略"></a>七、内存分配策略</h2><h3 id="一、内存分配策略（或对象提升（Promotion规则）"><a href="#一、内存分配策略（或对象提升（Promotion规则）" class="headerlink" title="一、内存分配策略（或对象提升（Promotion规则）"></a>一、内存分配策略（或对象提升（Promotion规则）</h3><p>如果对象在Eden出生并经过一次MinorGC后仍然存活，并且能被Survivor容纳的话，将被移动到Survivor空间中，并将对象年龄设置为1。对象在Survivor区中每熬过一次MinorGC ，年龄就增加1岁，当他的年龄增加到一定程度（默认15岁，其实每个JVM、每个GC都有所不同）时，就会被晋升到老年代中。</p>
<p>对象晋升老年代的年龄阈值，可以通过选项 <code>-XX:MaxTenuringThreshold</code>来设置。</p>
<p>针对不同年龄段的对象分配原则如下：</p>
<ul>
<li>优先分配到 Eden 区域</li>
<li>大对象直接分配到老年代，所以尽量避免程序中出现过多的大对象。</li>
<li>长期存活的对象分配到老年代</li>
<li>动态对象年龄判断<ul>
<li>如果Survivor区中年龄相同的所有对象大小总和大于Survivor空间的一半，年龄大于或等于该年龄的对象可以直接进入老年代，无需等到 <code>MaxTenuringThreshold</code> 中要求的年龄。</li>
</ul>
</li>
<li>空间分配担保：<ul>
<li><code>-XX：HandlePromotionFailure</code></li>
</ul>
</li>
</ul>
<h2 id="八、为对象分配内存：TLAB"><a href="#八、为对象分配内存：TLAB" class="headerlink" title="八、为对象分配内存：TLAB"></a>八、为对象分配内存：TLAB</h2><h3 id="一、为什么有TLAB（Thread-Local-Allocation-Buffer）？"><a href="#一、为什么有TLAB（Thread-Local-Allocation-Buffer）？" class="headerlink" title="一、为什么有TLAB（Thread Local Allocation Buffer）？"></a>一、为什么有TLAB（Thread Local Allocation Buffer）？</h3><p>堆区是线程共享区域，任何线程都可以访问到堆区中的共享数据。</p>
<p>由于对象实例的创建在JVM中非常频繁，因此在并发环境下从堆区中划分内存空间是线程不安全的</p>
<p>为了避免多个线程作同一地址，需要使用加锁机制，进而影响分配速度。</p>
<h3 id="二、什么是TLAB"><a href="#二、什么是TLAB" class="headerlink" title="二、什么是TLAB"></a>二、什么是TLAB</h3><p>从内存模型而不是垃圾收集的角度，对Eden区域继续进行划分，JVM 为每个线程划分一个私有缓存区域，它包含在 Eden 空间内。</p>
<p>多线程同时分配内存，使用 TLAB 可以避免一系列的非线程安全问题，同时还能够提升内存分配的吞吐量，因此我们可以将这种内存分配方式称为快速分配策略。</p>
<p>OpenJDK 衍生出来的 JVM 都提供了 TLAB 的设计。</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327114435294.png" alt="image-20220327114435294" style="zoom:80%;" />

<h3 id="三、TLAB的再说明"><a href="#三、TLAB的再说明" class="headerlink" title="三、TLAB的再说明"></a>三、TLAB的再说明</h3><p>尽管不是所有的对象实例都能够在TLAB中成功分配内存，但JVM确实是将TLAB作为内存分配的首选。</p>
<p>在程序中，开发人员可以通过选项”-XX”UseTLAB“ 设置是否开启TLAB空间。</p>
<p>默认情况下，TLAB空间的内存非常小，仅占有整个Eden空间的1%， 当然我们可以通过选项“-XX：TLABWasteTargetPercent” 设置TLAB空间所占Eden空间的百分比大小。</p>
<p>一旦对象在TLAB空间分配内存失败时，JVM就会尝试着通过使用加锁机制确保操作的原子性，从而直接Eden空间中分配内存</p>
<h2 id="九、堆空间的参数设置"><a href="#九、堆空间的参数设置" class="headerlink" title="九、堆空间的参数设置"></a>九、堆空间的参数设置</h2><ul>
<li>-XX：+PrintFlagsInitial : 查看所有的参数默认初始值。</li>
<li>-XX：+PrintFlagsFinal: 查看所有的参数的最终值（可能会存在修改，不再是初始值）</li>
<li>-Xms：初始堆空间内存（默认为物理内存的1/64）</li>
<li>-Xmx：最大堆空间内存（默认为物理内存的 1/4）</li>
<li>-Xmn：设置新生代的大小。（初始值及最大值）</li>
<li>-XX：NewRatio：设置新生代与老年代在对结构的占比</li>
<li>-XX：SurvivorRatio：设置新生代的Eden 和 S0/S1空间的比例</li>
<li>-XX：MaxTenuringThreshold：设置新生代的最大年龄</li>
<li>-XX：+PrintGCDetails：输出详细的GC处理日志。<ul>
<li>打印gc简要信息：① -XX：+PrintGC   ②  -verbose:gc</li>
</ul>
</li>
<li>-XX:HandlePromotionFailure：是否设置空间分配担保。</li>
<li>在发生Minor GC之前，虚拟机会检查老年代最大可用的连续空间是否大于新生代所有对象的总空间。<ul>
<li>如果大于，则此次Minor GC 是安全的</li>
<li>如果小于，则虚拟机会查看-XX：HandlePromotionFailure设置值是否允许担保失败。</li>
<li>如果HandlePromotionFaulure=true, 那么会继续检查老年代最大可用连续空间是否大于历次晋升到老年代的对象的平均大小。<ul>
<li>如果大于，则尝试进行一次Minor GC，但这次Minor GC 依然是由风险的。</li>
<li>如果小于，则改为进行一次Full GC 。</li>
</ul>
</li>
<li>如果HandlePromotionFailure=false，则改为进行一次Full GC。</li>
</ul>
</li>
<li>在JDK6 Update24之后，HandlePromotionFailure 参数不会再影响到虚拟机的空间分配担保策略，观察OpenJDK中的源码变化，虽然源码中还定义了HandlePromotionFailure 参数，但是在代码中已经不会再使用它。JDK6 Update24之后的规则变为只要老年代的连续空间大于新生代对象总大小或者历次晋升的平均大小就会进行Minor GC，否则将进行Full GC。</li>
</ul>
<h2 id="十、堆是分配对象存储的唯一选择吗？"><a href="#十、堆是分配对象存储的唯一选择吗？" class="headerlink" title="十、堆是分配对象存储的唯一选择吗？"></a>十、堆是分配对象存储的唯一选择吗？</h2><h3 id="一、堆是分配对象存储的唯一选择吗？"><a href="#一、堆是分配对象存储的唯一选择吗？" class="headerlink" title="一、堆是分配对象存储的唯一选择吗？"></a>一、堆是分配对象存储的唯一选择吗？</h3><p>在《深入理解Java虚拟机》中关于Java堆内存有这样一段描述：</p>
<ul>
<li>随着 JIT 编译器的发展与逃逸技术逐渐成熟，栈上分配、标量替换优化技术将会导致一些微妙的变化，所有的对象都分配到堆上也渐渐变的不那么“绝对”了。</li>
</ul>
<p>在Java虚拟机中，对象是在 Java 堆中分配内存的，这是一个普遍的常识。但是，有一种特殊情况，那就是经过逃逸分析（Escape Analysis）后发现，一个对象并没有逃逸出方法的话，那么就可能被优化成栈上分配。这样就无需在堆上分配内存。这样就无需在堆上分配内存，也无需进行垃圾回收了。这也是最常见的堆外存储技术。</p>
<p>此外，前面提到的基于 OpenJDK 深度定制的 TaoBao VM，其中创新的 GCIH（GC invisible heap）技术实现 off-heap ,将生命周期较长的 Java 对象从 heap 中移至 heap 外，并且 GC 不管 GCIH 内部的 Java 对象，以此达到降低 GC 的回收频率和提升 GC 的回收效率的目的。</p>
<h3 id="二、逃逸分析概述"><a href="#二、逃逸分析概述" class="headerlink" title="二、逃逸分析概述"></a>二、逃逸分析概述</h3><p>如何将堆上的对象分配到栈，需要使用逃逸分析手段。</p>
<p>这是一种可以有效减少Java程序中同步负载和内存堆分配压力的跨函数全局数据流分析算法。</p>
<p>通过逃逸分析，Java Hotspot 编译器能够分析出一个新的对象的引用的使用范围从而决定是否要将这个对象分配到堆上。</p>
<p>逃逸分析的基本行为就是分析对象动态作用域：</p>
<ul>
<li>当一个对象在方法中被定义后，对象只在方法内部使用，则认为没有发生逃逸。</li>
<li>当一个对象在方法中被定义后，它被外部方法所引用，则认为发生逃逸。例如作为调用参数传递到其他地方中。</li>
</ul>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">method</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token class-name">V</span> v <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">V</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token comment">// use v</span>
	<span class="token comment">// ...</span>
	v <span class="token operator">=</span> <span class="token keyword">null</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<blockquote>
<p>没有发生逃逸的对象，则可以分配到栈上，随着方法执行的结束，栈空间就被移除。</p>
</blockquote>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">StringBuffer</span> <span class="token function">createStringBuffer</span><span class="token punctuation">(</span><span class="token class-name">String</span> s1<span class="token punctuation">,</span> <span class="token class-name">String</span> s2<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token class-name">StringBuffer</span> sb <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringBuffer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	sb<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
	sb<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>s2<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">return</span> sb<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// 上述代码如果想要StringBuffer sb不逃出方法，可以这样写。</span>
<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">String</span> <span class="token function">createStringBuffer</span><span class="token punctuation">(</span><span class="token class-name">String</span> s1<span class="token punctuation">,</span> <span class="token class-name">String</span> s2<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token class-name">StringBuffer</span> sb <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringBuffer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	sb<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
	sb<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>s2<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">return</span> sb<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>    <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="三、参数设置"><a href="#三、参数设置" class="headerlink" title="三、参数设置"></a>三、参数设置</h3><p>在 JDK 6u23版本之后，HotSpot中默认就已经开启了逃逸分析。</p>
<p>如果使用的是较早的版本，开发人员则可以用过：</p>
<ul>
<li>选项“ -XX：+DoEscapeAnalysis”显示开启逃逸分析</li>
<li>通过选项“ -XX：+PrintEscapeAnalysis”查看逃逸分析的筛选结果。</li>
</ul>
<blockquote>
<p>结论：开发中使用局部变量，就不要定义在方法外。</p>
</blockquote>
<h3 id="四、逃逸分析：代码优化"><a href="#四、逃逸分析：代码优化" class="headerlink" title="四、逃逸分析：代码优化"></a>四、逃逸分析：代码优化</h3><p>使用逃逸分析，编译器可以对代码做如下优化：</p>
<ul>
<li>栈上分配。将堆分配转化栈分配。如果一个对象在子程序中分配，要使指向该对象的指针永远不会逃逸，对象可能是栈分配的候选，而不是堆分配。</li>
<li>同步省略。如果一个对象被发现只能从一个线程被访问到，那么对于这个对象的操作可以不考虑同步。</li>
<li>分离对象或标量替换。有的对象可能不需要作为一个连续的内存结构存在也可以被访问到，那么对象的部分（或全部）可以不存储在内存，而是存储在CPU寄存器中。</li>
</ul>
<h3 id="五、代码优化之栈上分配"><a href="#五、代码优化之栈上分配" class="headerlink" title="五、代码优化之栈上分配"></a>五、代码优化之栈上分配</h3><p>JIT 编译器在编译期间根据逃逸分析的结果，发现如果一个对象并没有逃逸出方法的话，就可能被优化成栈上分配。分配完成后没继续在调用栈内执行，最后线程结束，栈空间被回收，局部变量对象也被回收。这样就无需进行垃圾回收了。</p>
<p>常见的栈上分配的场景</p>
<ul>
<li>在逃逸分析中，已经说明了。分别是给成员变量赋值、方法返回值、实例引用传递。</li>
</ul>
<h3 id="六、代码优化之同步省略（消除）"><a href="#六、代码优化之同步省略（消除）" class="headerlink" title="六、代码优化之同步省略（消除）"></a>六、代码优化之同步省略（消除）</h3><p>线程同步的代价是相当高的，同步的后果是降低并发性和性能。</p>
<p>在动态编译同步块的时候，JIT编译器可以借助逃逸分析来判断同步块所使用的锁对象是否只能被一个线程访问而没有被发布到其他线程。如果没有，那么 JIT 编译器在编译这个同步块的时候就会取消对这部分代码的同步。这样就能大大提高并发性和性能。这个取消同步的过程就叫同步省略，也叫锁消除。</p>
<p>如以下代码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">f</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Object</span> hollis <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">synchronized</span><span class="token punctuation">(</span>hollis<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>hollis<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// 代码中会对hollis这个对象进行加锁，但是hollis对象的声明周期只在f()方法中，并不会被其他线程所访问到，所以在JIT编译阶段就会被优化掉。优化成：</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">f</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Object</span> hollis <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>hollis<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="七、代码优化之标量替换"><a href="#七、代码优化之标量替换" class="headerlink" title="七、代码优化之标量替换"></a>七、代码优化之标量替换</h3><p>标量（Scanlar）是指一个无法再分解成更小的数据的数据。Java中的原始数据类型就是标量。</p>
<p>相对的，那些还可以分解的数据叫做聚合量（Aggregate），Java中的对象就是聚合量，因为他可以分解成其他聚合量和标量。</p>
<p>在JIT阶段，如果经过逃逸分析，发现一个对象不会被外界访问的话，那么经过JIT优化，就会把这个对象拆解若干个其中包含的若干个成员变量来代替。这个过程就是标量替换。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token function">alloc</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">alloc</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Point</span> point  <span class="token operator">=</span><span class="token keyword">new</span> <span class="token class-name">Point</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"point.x="</span> <span class="token operator">+</span> point<span class="token punctuation">.</span>x <span class="token operator">+</span> <span class="token string">"; point.y"</span> <span class="token operator">+</span> y<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">class</span> <span class="token class-name">Point</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> x<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> y<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>以上代码，经过标量替换之后，就会变成：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">alloc</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">int</span> x <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> y <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">print</span><span class="token punctuation">(</span><span class="token string">"point.x="</span> <span class="token operator">+</span> x <span class="token operator">+</span> <span class="token string">"; point.y="</span> <span class="token operator">+</span> y<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>可以看到，Point这个聚合量经过逃逸分析后，发现他并没有逃逸，就被替换成两个标量了。那么标量替换有什么好处呢？就是可以大大减少堆内存的占用。因为一旦不需要创建对象了，那么就不再需要分配堆内存了。</p>
<p>标量替换为栈上分配提供了很好的基础。</p>
<p>标量替换参数设置：</p>
<ul>
<li>参数 -XX: +EliminateAllocations：开启了标量替换（默认打开），允许将对象打撒分配在栈上。</li>
</ul>
<p>上述代码在主函数中进行了1亿次alloc。调用进行对象创建，由于User对象实例需要占据约16字节的空间，因此累计分配空间达到将近1.5G。如果堆空间小于这个值，就必然会发生GC。使用如下参数运行上述代码：</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml">-server -Xmx100m -Xms -XX:+DoEscapeAnalysis -XX:+PrintGC -XX:+EliminateAllcations<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>这里使用参数如下：</p>
<ul>
<li>参数-server：启动Server模式，因为在Server模式下，才可以启动逃逸分析。</li>
<li>参数 -XX：+DoEscapeAnalysis：启用逃逸分析</li>
<li>参数-Xmx10m: 指定了堆空间最大为10MB</li>
<li>参数-XX：+PrintGC: 将打印GC日志。</li>
<li>参数 -XX：+EliminateAllocations: 开启了标量替换（默认打开），允许将对象打散分配在栈上，比如对象拥有id和name两个字段，那么这两个字段将会被视为两个独立的局部变量进行分配。</li>
</ul>
<h3 id="八、逃逸分析小结：逃逸分析并不成熟"><a href="#八、逃逸分析小结：逃逸分析并不成熟" class="headerlink" title="八、逃逸分析小结：逃逸分析并不成熟"></a>八、逃逸分析小结：逃逸分析并不成熟</h3><p>关于逃逸分析的论文在1999年就已经发表，但直到JDK1.6才有实现，而且这项技术到如今也并不是成熟的。</p>
<p>其根本原因就是无法保证逃逸分析的性能消耗一定能高于他的消耗。虽然经过逃逸分析可以做到标量替换、栈上分配、和锁消除。但是逃逸分析自身也是需要进行一系列复杂的分析的，这其实也是一个相对耗时的过程。</p>
<p>一个极端的例子，就是经过逃逸分析之后，发现没有一个对象是不逃逸的。那这个逃逸分析的过程就白白浪费掉了。</p>
<p>虽然这项技术并不成熟，但是它也是即使编译器优化技术中的一个十分重要的手段。</p>
<p>注意到有一些观点，认为通过逃逸分析，JVM会在栈上分配那些不会逃逸的对象，这在理论上是可行的，但是取决于JVM设计者的选择。Oracle Hotspot JVM中并未这么做，这一点在逃逸分析相关的文档里已经说明了，所以可以明确所有的对象都是创建在堆上的。</p>
<blockquote>
<p>目前很多书籍还是基于JDK 7以前的版本，JDK已经发生了很大变化，intern字符串的缓存和静态变量曾经都被分配在永久代上面，而永久代已经被元数据区取代，而是直接在堆上分配，所以这一点同样符合前面 一点的结论：对象实例都是分配在堆上的。</p>
</blockquote>
<h2 id="十一、小结"><a href="#十一、小结" class="headerlink" title="十一、小结"></a>十一、小结</h2><p>年轻代是对象的诞生、成长、消亡的区域，一个对象在这里产生、应用，最后被垃圾回收器收集、结束生命。</p>
<p>老年代放置长生命周期的对象，通常都是从Survivor区域筛选拷贝过来的Java对象。当然，也有特殊情况，我们知道普通的对象会被分配在TLAB上；如果对象较大，JVM会试图直接分配在Eden其他位置上；如果对象太大，完全无法在新生代找到足够长的连续空闲空间，JVM就会直接分配到老年代。</p>
<p>当GC只发生在年轻代中，回收年轻代对象的行为被称为MinorGC。当GC发生在老年代则被称为MajorGC或者FullGC。一般的，MinorGC发生的频率要比MajorGC高很多，即老年代中垃圾回收发生的频率将大大低于年轻代。</p>
<blockquote>
<p>巨人的肩膀：</p>
<p>尚硅谷 JVM</p>
</blockquote>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Gtwff</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://kuangty.gitee.io/2021/10/29/JVM/JVM%E5%A0%86/">https://kuangty.gitee.io/2021/10/29/JVM/JVM%E5%A0%86/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Gtwff</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/JVM-%E5%A0%86/">
                                    <span class="chip bg-color">JVM 堆</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/10/29/JVM/JVM%E6%96%B9%E6%B3%95%E5%8C%BA/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/2.jpg" class="responsive-img" alt="浅谈 JVM 方法区">
                        
                        <span class="card-title">浅谈 JVM 方法区</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-10-29
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/JVM/" class="post-category">
                                    JVM
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/JVM-%E6%96%B9%E6%B3%95%E5%8C%BA/">
                        <span class="chip bg-color">JVM 方法区</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/10/29/Redis/Redis_%E4%B8%BA%E4%BB%80%E4%B9%88%E5%8D%95%E7%BA%BF%E7%A8%8B%E7%9A%84Redis%E9%82%A3%E4%B9%88%E5%BF%AB/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/23.jpg" class="responsive-img" alt="为什么单线程的 Redis 能那么快">
                        
                        <span class="card-title">为什么单线程的 Redis 能那么快</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-10-29
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Redis/" class="post-category">
                                    Redis
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Redis-%E5%8D%95%E7%BA%BF%E7%A8%8B/">
                        <span class="chip bg-color">Redis 单线程</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2022</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">Gtwff</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">577.4k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2019";
                        var startMonth = "6";
                        var startDate = "28";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/kuangtianyu" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1575235124@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1575235124" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1575235124" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/kuang-tian-yu-59" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/kuang-tian-yu-59" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="99"
        src="/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
